<template>
    <div class="template-preview">
        <figure :loaded="status">
            <canvas ref="canvas"></canvas>
            <img src="https://img.podpartner.com/static/svgs-20230202/designer-upload-nodata.svg" alt="">
        </figure>

        <CommonProcessIcon :icons="icons" />
    </div>
</template>
<script>
export default {
    name: "DesignPrivew",
    props: {
        size: { type: String, default: '', require: false },
        models: { type: Array, default: () => [] },
        colors: { type: Array, default: () => [] },
        pieces: { type: Array, default: null },
        baseModel: { type: Object, default: null },
        baseColor: { type: Object, default: null },
    },
    data () {
        return {
            status: '',
            canvas: null,
            cache: {},
        };
    },
    computed: {
        // 基础预览效果
        wather () {
            return [this.baseColor, this.colors, this.baseModel, this.models]
        },

        icons () {
            const result = []
            const pieces = this.pieces || [];
            pieces.find(i => i.custom_count > 0) && result.push('custom')
            pieces.find(i => (i.type == 1 || !i.type) && i.output_img) && result.push('dtg')
            pieces.find(i => i.type == 2 && i.output_img) && result.push('emb')
            return result
        }

    },
    watch: {
        wather: {
            immdiate: false,
            deep: true,
            handler () {
                this.drawer();
            },
        }
    },
    methods: {
        jump (route) {
            this.$router.push(route)
        },
        // 加载图片
        loadImage (url) {

            let loader = this.cache[url];

            if (loader && loader.status == "complete") {
                // 已经有图片了，加载已完成
                return Promise.resolve(loader.image);
            } else if (loader && loader.status == "loading") {
                // 加载中的
                return new Promise((resolve, reject) => {
                    loader.callback.push((err) => {
                        if (loader.image) {
                            resolve(loader.image);
                        } else {
                            reject(err);
                        }
                    });
                });
            } else {

                // 没有图片
                // 或是图片加载失败
                const loader = {
                    count: 3, // 加载次数
                    image: null,
                    url: this.$getImageUrl(url, this.size),
                    status: "loading",
                    callback: [],
                };

                const createImage = () => {
                    const img = new Image();
                    img.onload = () => {
                        loader.image = img;
                        loader.status = "complete";
                        loader.callback.map((cb) => cb(img));
                        loader.callback = [];
                    };
                    img.onerror = (err) => {
                        loader.count -= 1;
                        if (loader.count > 0) {
                            setTimeout(createImage, 500);
                        } else {
                            // 加载多次都失败了
                            loader.status = "error";
                            loader.callback.map((cb) => cb(err));
                            loader.callback = [];
                            delete this.cache[url];
                        }
                    };
                    img.crossOrigin = "anonymous";
                    img.src = loader.url;
                };

                return new Promise((resolve, reject) => {
                    loader.callback.push((err) => {
                        if (loader.image) {
                            resolve(loader.image);
                        } else {
                            reject(err);
                        }
                    });
                    this.cache[url] = loader;
                    createImage();
                });
            }
        },


        getDefaultModel () {

            if (this.baseModel) {
                return this.baseModel
            } else if (this.models.length > 0) {
                // 默认显示平铺图，如果没有再显示有的模特
                const models = this.models
                const tag_name = 'flat lay';
                const tag_able = ['hanging', 'flat lay', 'model'].filter(i => models.find(m => (m.model_tag || 'hanging') == i))
                const tag_active = tag_able.indexOf(tag_name) >= 0 ? tag_name : tag_able[0];
                return models.find(m => (m.model_tag || 'hanging') == tag_active)
            } else {
                return {}
            }

        },

        drawer () {

            const color = this.baseColor || (this.colors[0] || {});
            const model = this.getDefaultModel();

            this.canvas = this.$refs.canvas;

            if (!this.canvas) {
                this.status = 'error';
            } else if (!model.model_url) {
                this.status = 'error';
            } else {
                const promises = [];
                const taxture = this.$modelColorTaxture(model, color)

                if (taxture) {
                    // 有纹理
                    promises.push(this.loadImage(taxture));
                } else {
                    promises.push(Promise.resolve(color.color_num || ''));
                }

                promises.push(this.loadImage(model.model_url));

                this.status = 'loading';
                Promise.all(promises).then(result => {

                    const taxture = result[0];
                    const mask = result[1];

                    const canvas = this.canvas;
                    const parent = canvas.parentNode;
                    const rect = parent.getBoundingClientRect()
                    const ctx = canvas.getContext("2d");

                    const type = Object.prototype.toString.call(taxture);

                    canvas.width = rect.width * 2;
                    canvas.height = rect.height * 2;
                    // 清画布
                    ctx.clearRect(0, 0, canvas.width, canvas.height);

                    if (!taxture) {
                        // 没有颜色
                    } else if (type == '[object HTMLImageElement]') {
                        // 画图
                        ctx.drawImage(taxture, 0, 0, taxture.width, taxture.height, 0, 0, canvas.width, canvas.height);
                    } else if (type == '[object String]') {
                        // 画底色
                        ctx.fillStyle = this.$modelBackgroundColor(color.color_num, model) || "";
                        ctx.fillRect(0, 0, canvas.width, canvas.height);
                    }

                    // 画图
                    ctx.drawImage(mask, 0, 0, mask.width, mask.height, 0, 0, canvas.width, canvas.height);
                    this.status = 'loaded'
                }).catch(error => {
                    // console.log(error)
                    this.status = 'error';
                })
            }
        },

        // 预览
        // priview (url, color) {
        //     if (url) {
        //         let index = 0;
        //         let urls = [this.$getImageUrl(url, "large")];
        //         imagePreview({
        //             initIndex: index,
        //             images: urls,
        //         });
        //         let imgDom = document.getElementsByClassName(
        //             "image-preview__image"
        //         )[0];
        //         imgDom.style.backgroundColor = color || "#eee";
        //     }
        // },
    },
    mounted () {
        this.drawer();
    }
};
</script>
<style>
.image-preview {
    display: flex;
    align-items: center;
    justify-content: center;
}
.image-preview__image {
    width: auto !important;
}
</style>
<style lang="scss" scoped>
.template-tip {
    &::v-deep .popper-content {
        padding: 0 !important;
    }
}
.template-preview {
    position: relative;
    figure {
        width: 100%;
        padding-bottom: 100%;
        position: relative;
        overflow: hidden;

        &[loaded='loading'] {
            background-image: url(@/assets/images/loading.gif);
            background-position: center;
            background-size: 32px 32px;
            background-repeat: no-repeat;
        }

        &[loaded='error'] {
            svg,
            img {
                display: block;
            }
        }

        &[loaded='loaded'] {
            canvas {
                display: block;
            }
        }

        svg,
        img,
        canvas {
            display: none;
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
        }

        &::after {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            // border-radius: 6px;
            // border: 1px solid #f2f2f2;
        }
        > span {
            z-index: 0;
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }
    }

    .process-icon {
        position: absolute;
        left: 0;
        top: 0;
        display: flex;
        span {
            width: 20px;
            height: 20px;
            padding: 1px;
            background: #ffffff;
            border: 1px solid #ebebeb;
            box-sizing: border-box;
            border-radius: 24px;
            margin-right: 6px;
            position: relative;

            &::before {
                content: '';
                position: absolute;
                width: 16px;
                height: 16px;
                left: 50%;
                top: 50%;
                transform: translate(-50%, -50%);
                background-size: 100% 100%;
            }

            &[name='dtg']::before {
                background-image: url(@/assets/images/designer/designer-dtg.png);
            }
            &[name='emb']::before {
                background-image: url(@/assets/images/designer/designer-emb.png);
            }
            &[name='custom']::before {
                background-image: url(@/assets/images/designer/designer-custom.png);
            }

            em,
            a {
                position: absolute;
                left: 50%;
                top: -36px;
                transform: translateX(-50%);
                line-height: 32px;
                padding: 0 16px;
                background: #212121;
                white-space: nowrap;
                display: none;
                color: #fff;
                border-radius: 6px;
                &::before {
                    content: '';
                    width: 0;
                    height: 0;
                    left: 50%;
                    top: 100%;
                    transform: translateX(-50%);
                    border-top: 3px solid #212121;
                    border-left: 4px solid transparent;
                    border-right: 4px solid transparent;
                    position: absolute;
                }
            }

            a {
                text-decoration: underline;
            }

            &:hover em,
            &:hover a {
                display: block;
            }
        }
    }

    .tooltip {
        position: absolute !important;
        width: 24px;
        height: 24px;
        top: 0px;
        left: 0px;
        cursor: default;

        img {
            width: 24px;
            height: 24px;
            &.large {
                left: -8px;
                top: -8px;
            }
        }

        a {
            color: #fff;
            text-decoration: underline;
            cursor: pointer;
            &:hover {
                text-decoration: none;
            }
        }
    }
}

.template-preview-popover {
    // display: flex;
    // flex-direction: column;
    // align-items: center;
    margin: -12px;
    max-width: 512px;
    padding: 4px;
    box-sizing: border-box;
    font-size: 0;
    h3 {
        // width: 100%;
        font-size: 14px;
        font-weight: normal;
        color: #000000;
        height: 39px;
        line-height: 40px;
        border-bottom: 1px solid #dcdcdc;
        text-align: center;
        margin-bottom: 4px;
    }

    figure {
        display: inline-block;
        vertical-align: top;
        width: 160px;
        margin: 4px 8px 10px;
        position: relative;

        span {
            display: block;
            padding-bottom: 100%;
            position: relative;
            background: #f7f7f7;
            img {
                max-width: 100%;
                max-height: 100%;
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background-image: url();
            }
        }

        small {
            display: block;
            text-align: center;
            top: 100%;
            margin-top: 7px;
            font-size: 14px;

            color: #000000;
            line-height: 18px;
        }
    }
}
</style>
